from logging.config import dictConfig

import asyncio
import locale
import quamash
import time
import websockets
from PyQt5.QtCore import pyqtSlot, QObject, pyqtSignal, Qt, QTranslator, QCoreApplication
from PyQt5.QtGui import QIcon, QPixmap
import shutil
import os
import logging
import sys

from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineProfile

from mrc_pymata_aio.pymata_core import PymataCore
from tools_pack.help_pack import get_ini_value, guess_port_name, set_ini_value
from tools_pack.languages import getsystemlanguage
from tools_pack.log_conf import log_directory, StreamToLogger, LOGGING
from tools_pack.mrc_tools import MrcMataIOT

log_dir=log_directory()
log_dir.check_directorys()
dictConfig(LOGGING)

stderr_logger = logging.getLogger('stderr')
sys.stderr = StreamToLogger(stderr_logger)
stdout_logger = logging.getLogger('stdout')
# sys.stdout = StreamToLogger(stdout_logger)
loger=logging.getLogger("metas")

__author__ = 'jack'
from PyQt5 import QtWebEngineWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QFileDialog, QMessageBox, QInputDialog, QLineEdit
import sys
import _thread
from arduino_web_server import run_server
from tools_pack import global_shared
global_shared._init() #先必须在主模块初始化（只在Main模块需要一次即可）

width = get_ini_value('ui_conf', 'width')
height = get_ini_value('ui_conf', 'height')
cc_ip = get_ini_value('metas_conf', 'ip')
cc_port = get_ini_value('metas_conf', 'port')

first_open=get_ini_value('metas_conf','first_open')
if first_open=='0':   #第一次打开程序设置用户习惯语言
    language = "en"  # 默认
    all_language = ['zh_cn', 'en']
    system_language = locale.getdefaultlocale()[0]  # 系统默认的语言 如zh_cn
    system_language = system_language.lower()  # 全部转成小写
    if system_language in all_language:
        language = system_language
    set_ini_value('metas_conf', 'language',language.encode('utf-8'))

import ui_rc
app = QApplication(sys.argv)

class MetasPage(QtWebEngineWidgets.QWebEnginePage):
    '''
    浏览器页面的重载
    '''
    def __init__(self,profile=None,parent=None):
        super(MetasPage,self).__init__(profile,parent)
        language_src = getsystemlanguage()
        self.trans = QTranslator()
        self.trans.load(language_src)  # 没有后缀.qm
        app.installTranslator(self.trans)

    def javaScriptAlert(self, QUrl, p_str):
        '''
        web中js中alert函数对话框显示函数
        :param QUrl:
        :param p_str: message
        :return:
        '''
        tip = QMessageBox(webView)
        tip.setIcon(QMessageBox.Information)
        tip.setText(p_str)
        tip.setWindowTitle(self.tr('MRC information tips')) #MRC信息提示
        tip.exec()


    def javaScriptConfirm(self, QUrl, p_str):
        '''
        web中js中confirm函数对话框显示函数
        :param QUrl:
        :param p_str: message
        :return:
        '''
        tip = QMessageBox(webView)
        tip.setIcon(QMessageBox.Information)
        tip.setText(p_str)
        tip.setWindowTitle(self.tr('MRC information tips'))
        tip.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = tip.exec()
        if close == QMessageBox.Yes:
            return True
        else:
            return False

    def javaScriptPrompt(self, QUrl, p_str, p_str_1):
        text,ok= QInputDialog.getText(webView,self.tr('MRC information tips'),p_str,QLineEdit.Normal,p_str_1)
        if ok and text!=None and text!='':
            return True,text
        else:
            return False,None

    @pyqtSlot(str)
    def ui_text_set(self, lange):
        app.removeTranslator(self.trans)

        self.trans = QTranslator()
        self.trans.load(":/i18n/zh-cn.qm")  # 没有后缀.qm
        app.installTranslator(self.trans)





class MetasWeb(QtWebEngineWidgets.QWebEngineView):

    BocklyCloseServer=pyqtSignal()
    choose_language_signal = pyqtSignal(['QString'])

    def __init__(self):
        super(MetasWeb,self).__init__()

        language_src=getsystemlanguage()
        self.trans = QTranslator()
        self.trans.load(language_src)  # 没有后缀.qm
        app.installTranslator(self.trans)

        self.setWindowTitle(self.tr('MRC program'))
        profile = QWebEngineProfile(self)
        self.webpage = MetasPage(profile, self)   #使用自定义页面引擎类
        self.setPage(self.webpage)


    def file_save(self):
        '''
        2017-12-13 add by jack
        获取用户选择的保存目录
        :return:
        '''
        fileName, _ = QFileDialog.getSaveFileName(self,self.tr("Save MRC program project file"),"","Text Files (*.mt)")
        return fileName


    def _downloadRequested(self,item): # QWebEngineDownloadItem
        '''
        2017-12-13 add by jack
        设置保存文件路径
        :param item:
        :return:
        '''
        # print('downloading to', item.path())
        file_path=self.file_save()
        item.setPath(file_path)
        item.accept()


    def additional_settings(self):
        icon = QIcon()
        icon.addPixmap(QPixmap("src\mrc_logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.showMaximized()

        self.page().profile().downloadRequested.connect(self._downloadRequested)

        if os.path.isdir(os.path.join(self.page().profile().cachePath(),'Cache')):
            shutil.rmtree(os.path.join(self.page().profile().cachePath(),'Cache'))

    def closeEvent(self, event):
        self.close = QMessageBox(self)
        self.close.setText(self.tr("Is MRC program software turned off?")) #是否关闭MRC编程软件?
        self.close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = self.close.exec()

        if close == QMessageBox.Yes:
            self.BocklyCloseServer.connect(handler.closeServer)
            self.BocklyCloseServer.emit()
            event.accept()
        else:
            event.ignore()

    @pyqtSlot(str)
    def ui_text_set(self,lange):
        app.removeTranslator(self.trans)

        self.trans = QTranslator()
        self.trans.load(":i18n/"+lange+".qm")  # 没有后缀.qm
        app.installTranslator(self.trans)

        self.setWindowTitle(self.tr('MRC program'))

        self.choose_language_signal.connect(self.webpage.ui_text_set)
        self.choose_language_signal.emit(lange)






class CallHandler(QObject):
    """
    启动pymata_iao+websocket服务器
    只要能作用pyqt打开自带的浏览器，不能用外置的浏览器
    """
    core = None
    # def __init__(self):
    #     super(CallHandler,self).__init__()
    #     self.core=None
    choose_language_signal = pyqtSignal( ['QString'])

    @pyqtSlot()
    def test(self):
        print('call received')

    @pyqtSlot()
    def run_websocket(self):
        ip = get_ini_value('bockly', 'ip')
        port = get_ini_value('bockly', 'port')
        tmp_user_use_port=global_shared.get_value('tmp_user_use_port',None)

        com_port = guess_port_name()
        tmp_user_use_port = global_shared.get_value('tmp_user_use_port', None)
        if tmp_user_use_port != None:  # 判断用户是否选择端口
            com_port = tmp_user_use_port

        connect_type=get_ini_value('connect','type')
        if connect_type=='2':
            wifi_ip=get_ini_value('connect','wifi_ip')
            wifi_port=get_ini_value('connect','wifi_port')
            self.core = PymataCore(ip_address=wifi_ip,ip_port=int(wifi_port),ip_handshake='',log_output=True)
        else:
            self.core = PymataCore(com_port=com_port,log_output=True)
        # asyncio.ensure_future(self.core.send_reset(), loop=loop)
        asyncio.ensure_future(self.core.start_aio(), loop=loop)
        server = MrcMataIOT(self.core)
        server.http_server(block_ip=ip,block_port=port)

    @pyqtSlot()
    def closeServer(self):
        if self.core!=None:
            asyncio.ensure_future(self.core.shutdown(), loop=loop)
            # print('shutdown borad')

    @pyqtSlot(str)
    def choose_language(self,lang):
        self.choose_language_signal.connect(webView.ui_text_set)
        self.choose_language_signal.emit(lang)





loop = quamash.QEventLoop(app)
asyncio.set_event_loop(loop)  # NEW must set the event loop

webView = MetasWeb()
webView.additional_settings()

#----------------使用通道的方式，是的javascript可以调用pyqt对象的槽----------
channel = QWebChannel()
handler = CallHandler()
channel.registerObject('handler', handler)
webView.page().setWebChannel(channel)
#----------------end------------------------------------------------------------

loger.info("Blocklyduino can now be accessed athttp://%s:%s/" % (cc_ip, cc_port))
_thread.start_new_thread(run_server, (cc_ip, int(cc_port)))
webView.show()
http_url = 'http://%s:%s' % (cc_ip, cc_port)
webView.load(QtCore.QUrl(http_url))
loop.run_forever()
# sys.exit(app.exec_())

